package com.example.qihuibao.module.main

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.qihuibao.XApplication
import com.example.qihuibao.bean.*
import com.example.qihuibao.constant.Config
import com.example.qihuibao.constant.Global
import com.example.qihuibao.dao.MyDatabase
import com.example.qihuibao.network.RetrofitManager
import com.example.qihuibao.network.RetrofitModel
import com.example.qihuibao.utils.CommonUtil
import com.example.qihuibao.utils.DES3Util
import com.google.gson.Gson
import com.maning.updatelibrary.InstallUtils
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.io.FileOutputStream

/**
 *@author: cww
 *@desc:
 *@date: 4/22/23 11:18 AM
 */
class MainRepository {
    fun queryEnterpriseInfo(req:BaseReqBean) : LiveData<RspQueryEnterpriseInfoBean> {
//        val defaultRspBean = Gson().fromJson(CommonUtil.getObjFromAssetsJson("enterprise.json"), RspQueryEnterpriseInfoBean::class.java)
//        return RetrofitModel.requestEntry(req, defaultRspBean)
        val data = MutableLiveData<RspQueryEnterpriseInfoBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspQueryEnterpriseInfoBean>{
            override fun onSucced(result: RspQueryEnterpriseInfoBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    Thread {
                        var rspBean = MyDatabase.db.enterpriseInfoDao().queryInId(req.CorpID)
                        if (rspBean == null) {
                            rspBean = RspQueryEnterpriseInfoBean()
                        }else {
                            rspBean.RetCode = "0"
                        }
                        data.postValue(rspBean)
                    }.start()
                }
            }

            override fun onFailed(errMsg: String) {
                data.value = RspQueryEnterpriseInfoBean()
            }
        })
        return data
    }

    fun updateEnterpriseInfo(req:ReqUpdateEnterpriseInfoBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun queryDepartmentInfo(req:BaseReqBean) : LiveData<RspQueryDepartmentInfoBean> {
//        val defaultRspBean = Gson().fromJson(CommonUtil.getObjFromAssetsJson("department.json"), RspQueryDepartmentInfoBean::class.java)
//        return RetrofitModel.requestEntry(req, defaultRspBean)
        val data = MutableLiveData<RspQueryDepartmentInfoBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspQueryDepartmentInfoBean>{
            override fun onSucced(result: RspQueryDepartmentInfoBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    Thread {
                        val bean = RspQueryDepartmentInfoBean()
                        bean.DepList = MyDatabase.db.departmentInfoDao().queryAll()
                        if (!bean.DepList.isNullOrEmpty()) {
                            bean.RetCode = "0"
                        }
                        data.postValue(bean)
                    }.start()
                }
            }

            override fun onFailed(errMsg: String) {
                data.value = RspQueryDepartmentInfoBean()
            }
        })
        return data
    }

    fun updateDepartmentInfo(req:ReqUpdateDepartmentInfoBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun addDepartmentInfo(req:ReqAddDepartmentInfoBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun deleteDepartmentInfo(req:ReqDeleteDepartmentInfoBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun queryEmployInfo(req:ReqQueryEmployInfoBean) : LiveData<RspQueryEmployInfoBean> {
//        val defaultRspBean = when(req.PageNo) {
//            1 -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("employ1.json"), RspQueryEmployInfoBean::class.java)
//            2 -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("employ2.json"), RspQueryEmployInfoBean::class.java)
//            else -> RspQueryEmployInfoBean()
//        }
//        return RetrofitModel.requestEntry(req, defaultRspBean)
        val data = MutableLiveData<RspQueryEmployInfoBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspQueryEmployInfoBean>{
            override fun onSucced(result: RspQueryEmployInfoBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    Thread {
                        val rspBean = RspQueryEmployInfoBean()
                        rspBean.EmpList = MyDatabase.db.employInfoDao().queryAll()
                        if (!rspBean.EmpList.isNullOrEmpty()) {
                            rspBean.RetCode = "0"
                            rspBean.HasNext = "0"
                        }
                        data.postValue(rspBean)
                    }.start()
                }
            }

            override fun onFailed(errMsg: String) {
                data.value = RspQueryEmployInfoBean()
            }
        })
        return data
    }

    fun updateEmployInfo(req:ReqUpdateEmployInfoBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun addEmployInfo(req:ReqAddEmployInfoBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun deleteEmployInfo(req:ReqDeleteEmployInfoBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun queryCanteenInfo(req:ReqQueryCanteenInfoBean) : LiveData<RspQueryCanteenInfoBean> {
//        val defaultRspBean = when(req.CantID) {
//            "01" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1.json"), RspQueryCanteenInfoBean::class.java)
//            "02" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen2.json"), RspQueryCanteenInfoBean::class.java)
//            else -> RspQueryCanteenInfoBean()
//        }
//        return RetrofitModel.requestEntry(req, defaultRspBean)
        val data = MutableLiveData<RspQueryCanteenInfoBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspQueryCanteenInfoBean>{
            override fun onSucced(result: RspQueryCanteenInfoBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    Thread {
                        var rspBean = MyDatabase.db.canteenInfoDao().queryByCanteenId(req.CantID)
                        if (rspBean == null) {
                            rspBean = RspQueryCanteenInfoBean()
                        }else {
                            rspBean.RetCode = "0"
                        }
                        data.postValue(rspBean)
                    }.start()
                }
            }

            override fun onFailed(errMsg: String) {
                data.value = RspQueryCanteenInfoBean()
            }
        })
        return data
    }

    fun updateCanteenInfo(req:ReqUpdateCanteenInfoBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun queryMealInfo(req:ReqQueryMealInfoBean) : LiveData<RspQueryMealInfoBean> {
//        val defaultRspBean = when(req.CantID) {
//            "01" -> when(req.MealID) {
//                "01" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_meal1.json"), RspQueryMealInfoBean::class.java)
//                "02" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_meal2.json"), RspQueryMealInfoBean::class.java)
//                "03" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_meal3.json"), RspQueryMealInfoBean::class.java)
//                "04" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_meal4.json"), RspQueryMealInfoBean::class.java)
//                "05" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_meal5.json"), RspQueryMealInfoBean::class.java)
//                else -> RspQueryMealInfoBean()
//            }
//            "02" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen2_meal1.json"), RspQueryMealInfoBean::class.java)
//            else -> RspQueryMealInfoBean()
//        }
//        return RetrofitModel.requestEntry(req, defaultRspBean)
        val data = MutableLiveData<RspQueryMealInfoBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspQueryMealInfoBean>{
            override fun onSucced(result: RspQueryMealInfoBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    Thread {
                        var rspBean = MyDatabase.db.mealInfoDao().queryInId(req.CantID, req.MealID)
                        if (rspBean == null) {
                            rspBean = RspQueryMealInfoBean()
                        }else {
                            rspBean.RetCode = "0"
                        }
                        data.postValue(rspBean)
                    }.start()
                }
            }

            override fun onFailed(errMsg: String) {
                data.value = RspQueryMealInfoBean()
            }
        })
        return data
    }

    fun updateMealInfo(req:ReqUpdateMealInfoBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun queryFees(req:ReqQueryFeesBean) : LiveData<RspQueryFeesBean> {
//        val defaultRspBean = when(req.CantID) {
//            "01" -> when(req.MealID) {
//                "01" -> when(req.FeeID) {
//                    "01" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_meal1_fee1.json"), RspQueryFeesBean::class.java)
//                    "02" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_meal1_fee2.json"), RspQueryFeesBean::class.java)
//                    else -> RspQueryFeesBean()
//                }
//                else -> RspQueryFeesBean()
//            }
//            "02" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen2_meal1_fee1.json"), RspQueryFeesBean::class.java)
//            else -> RspQueryFeesBean()
//        }
//        return RetrofitModel.requestEntry(req, defaultRspBean)
        val data = MutableLiveData<RspQueryFeesBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspQueryFeesBean>{
            override fun onSucced(result: RspQueryFeesBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    Thread {
                        var rspBean = MyDatabase.db.feesInfoDao().queryInId(req.CantID, req.MealID)
                        if (rspBean == null) {
                            rspBean = RspQueryFeesBean()
                        }else {
                            rspBean.RetCode = "0"
                        }
                        data.postValue(rspBean)
                    }.start()
                }
            }

            override fun onFailed(errMsg: String) {
                data.value = RspQueryFeesBean()
            }
        })
        return data
    }

    fun updateFees(req:ReqUpdateFeesBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun addFees(req:ReqAddFeesBean) : LiveData<RspAddFeesBean> {
//        return RetrofitModel.requestEntry(req, RspAddFeesBean())
        val data = MutableLiveData<RspAddFeesBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspAddFeesBean>{
            override fun onSucced(result: RspAddFeesBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    onFailed("出错了")
                }
            }

            override fun onFailed(errMsg: String) {
                val rspBean = RspAddFeesBean()
                rspBean.RetMsg = errMsg
                data.value = rspBean
            }
        })
        return data
    }

    fun deleteFees(req:ReqDeleteFeesBean) : LiveData<BaseRspBean> {
//        return RetrofitModel.requestEntry(req, BaseRspBean())
        return setReq(req)
    }

    fun heartbeat(req:ReqHeartbeatBean) : LiveData<RspHeartbeatBean> {
        return RetrofitModel.requestEntry(req, RspHeartbeatBean())
    }

    fun queryFaceFile(req:ReqQueryFaceFileBean) : LiveData<RspQueryFaceFileBean> {
//        val defaultRspBean = when(req.PageNo) {
//            1 -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("facefile_page1.json"), RspQueryFaceFileBean::class.java)
//            2 -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("facefile_page2.json"), RspQueryFaceFileBean::class.java)
//            else -> RspQueryFaceFileBean()
//        }
//        return RetrofitModel.requestEntry(req, defaultRspBean)
        val data = MutableLiveData<RspQueryFaceFileBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspQueryFaceFileBean>{
            override fun onSucced(result: RspQueryFaceFileBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    Thread {
                        val rspBean = RspQueryFaceFileBean()
                        rspBean.FaceFileList = MyDatabase.db.faceFileInfoDao().queryAll()
                        if (!rspBean.FaceFileList.isNullOrEmpty()) {
                            rspBean.RetCode = "0"
                            rspBean.HasNext = "0"
                        }
                        data.postValue(rspBean)
                    }.start()
                }
            }

            override fun onFailed(errMsg: String) {
                data.value = RspQueryFaceFileBean()
            }
        })
        return data
    }

    fun downloadFaceFile(faceFile:RspQueryFaceFileBean.FaceFile) : LiveData<BaseRspBean> {
        val data = MutableLiveData<BaseRspBean>()
        val rsp = BaseRspBean()
        val req = ReqDownloadFaceFileBean(faceFile.EmpID)
        //
        val body = ReqBean(DES3Util.EncryptData(Gson().toJson(req), Global.CorpKey), Global.CorpID)//加密请求数据
        RetrofitManager.getInstance().httpApi./*post(body)*/downLoad(faceFile.FaceFileName)?.enqueue(object : Callback<ResponseBody>{
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                val inputStream = response.body()?.byteStream()
                if (inputStream != null) {
                    try {
                        if (!File(Global.facePath).exists()) {
                            File(Global.facePath).mkdirs()
                        }
                        val fos = FileOutputStream(Global.facePath + req.EmpID + ".png")
                        val buffer = ByteArray(4096)
                        var len = inputStream.read(buffer)
                        while (len != -1){
                            fos.write(buffer,0,len)
                            len = inputStream.read(buffer)
                        }
                        fos.close()
                        inputStream.close()
                        rsp.RetCode = "0"
                    }catch (e:Exception) {
                        e.printStackTrace()
                    }
                }else {
                    rsp.RetCode = "-1"
                }
                data.value = rsp
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                rsp.RetCode = "-1"
                data.value = BaseRspBean()
            }
        })

        return data
    }

    fun queryOrderInfo(req:ReqQueryOrderInfoBean) : LiveData<RspQueryOrderInfoBean> {
//        val defaultRspBean = when(req.CantID) {
//            "01" -> when(req.PageNo) {
//                1 -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_order_page1.json"), RspQueryOrderInfoBean::class.java)
//                2 -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_order_page2.json"), RspQueryOrderInfoBean::class.java)
//                else -> RspQueryOrderInfoBean()
//            }
//            "02" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen2_order_page1.json"), RspQueryOrderInfoBean::class.java)
//            else -> RspQueryOrderInfoBean()
//        }
//        return RetrofitModel.requestEntry(req, defaultRspBean)
        val data = MutableLiveData<RspQueryOrderInfoBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspQueryOrderInfoBean>{
            override fun onSucced(result: RspQueryOrderInfoBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    Thread {
                        val rspBean = RspQueryOrderInfoBean()
                        rspBean.OrderList = MyDatabase.db.orderInfoDao().queryAll()
                        if (!rspBean.OrderList.isNullOrEmpty()) {
                            rspBean.RetCode = "0"
                            rspBean.HasNext = "0"
                        }
                        data.postValue(rspBean)
                    }.start()
                }
            }

            override fun onFailed(errMsg: String) {
                data.value = RspQueryOrderInfoBean()
            }
        })
        return data
    }

    fun useConsume(req:ReqUseConsumeBean) : LiveData<RspUseConsumeBean> {
        return RetrofitModel.requestEntry(req, RspUseConsumeBean())
    }

    fun queryPayDetail(req:ReqQueryPayDetailBean) : LiveData<RspQueryPayDetailBean> {
//        val defaultRspBean = when(req.CantID) {
//            "01" -> when(req.PageNo) {
//                1 -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_paydetail_page1.json"), RspQueryPayDetailBean::class.java)
//                2 -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_paydetail_page2.json"), RspQueryPayDetailBean::class.java)
//                else -> RspQueryPayDetailBean()
//            }
//            "02" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen2_paydetail_page1.json"), RspQueryPayDetailBean::class.java)
//            else -> RspQueryPayDetailBean()
//        }
//        return RetrofitModel.requestEntry(req, defaultRspBean)
        val data = MutableLiveData<RspQueryPayDetailBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspQueryPayDetailBean>{
            override fun onSucced(result: RspQueryPayDetailBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    Thread {
                        val rspBean = RspQueryPayDetailBean()
                        rspBean.PayList = MyDatabase.db.payInfoDao().queryAll()
                        if (!rspBean.PayList.isNullOrEmpty()) {
                            rspBean.RetCode = "0"
                            rspBean.HasNext = "0"
                        }
                        data.postValue(rspBean)
                    }.start()
                }
            }

            override fun onFailed(errMsg: String) {
                data.value = RspQueryPayDetailBean()
            }
        })
        return data
    }

    fun queryUseDetail(req:ReqUseDetailBean) : LiveData<RspUseDetailBean> {
//        val defaultRspBean = when(req.CantID) {
//            "01" -> when(req.PageNo) {
//                1 -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_usedetail_page1.json"), RspUseDetailBean::class.java)
//                2 -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen1_usedetail_page2.json"), RspUseDetailBean::class.java)
//                else -> RspUseDetailBean()
//            }
//            "02" -> Gson().fromJson(CommonUtil.getObjFromAssetsJson("canteen2_usedetail_page1.json"), RspUseDetailBean::class.java)
//            else -> RspUseDetailBean()
//        }
//        return RetrofitModel.requestEntry(req, defaultRspBean)
        val data = MutableLiveData<RspUseDetailBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspUseDetailBean>{
            override fun onSucced(result: RspUseDetailBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    Thread {
                        val rspBean = RspUseDetailBean()
                        rspBean.UseList = MyDatabase.db.useInfoDao().queryAll()
                        if (!rspBean.UseList.isNullOrEmpty()) {
                            rspBean.RetCode = "0"
                            rspBean.HasNext = "0"
                        }
                        data.postValue(rspBean)
                    }.start()
                }
            }

            override fun onFailed(errMsg: String) {
                data.value = RspUseDetailBean()
            }
        })
        return data
    }

    fun balanceNotice(req:ReqBalanceNotifyBean) : LiveData<RspBalanceNotifyBean> {
//        return RetrofitModel.requestEntry(req, RspBalanceNotifyBean())
        val data = MutableLiveData<RspBalanceNotifyBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspBalanceNotifyBean>{
            override fun onSucced(result: RspBalanceNotifyBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    onFailed("出错了")
                }
            }

            override fun onFailed(errMsg: String) {
                val rspBean = RspBalanceNotifyBean()
                rspBean.RetMsg = errMsg
                data.value = rspBean
            }
        })
        return data
    }

    fun etTicketUseConsume(req:ReqETTicketUseConsumeBean) : LiveData<RspETTicketUseConsumeBean> {
//        return RetrofitModel.requestEntry(req, RspETTicketUseConsumeBean())
        val data = MutableLiveData<RspETTicketUseConsumeBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspETTicketUseConsumeBean>{
            override fun onSucced(result: RspETTicketUseConsumeBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    onFailed("出错了")
                }
            }

            override fun onFailed(errMsg: String) {
                val rspBean = RspETTicketUseConsumeBean()
                rspBean.RetMsg = errMsg
                data.value = rspBean
            }
        })
        return data
    }

    fun reverse(req:ReqReverseBean) : LiveData<RspReverseBean> {
//        return RetrofitModel.requestEntry(req, RspReverseBean())
        val data = MutableLiveData<RspReverseBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<RspReverseBean>{
            override fun onSucced(result: RspReverseBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    onFailed("出错了")
                }
            }

            override fun onFailed(errMsg: String) {
                val rspBean = RspReverseBean()
                rspBean.RetMsg = errMsg
                data.value = rspBean
            }
        })
        return data
    }

    //统一返回BaseRspBean的请求
    private fun <T:BaseReqBean> setReq(req:T):LiveData<BaseRspBean> {
        val data = MutableLiveData<BaseRspBean>()
        RetrofitModel.requestEntry2(req, object:RetrofitModel.Result<BaseRspBean>{
            override fun onSucced(result: BaseRspBean?) {
                if (result != null) {
                    data.value = result
                }else {
                    onFailed("出错了")
                }
            }

            override fun onFailed(errMsg: String) {
                val rspBean = BaseRspBean()
                rspBean.RetCode = "-1"
                rspBean.RetMsg = errMsg
                data.value = rspBean
            }
        })
        return data
    }
}